// pages/signUp/signUp.js
import __config from '../../config/env.js'
import validate from '../../utils/validate.js'
const app = getApp()

function getNowDate2(){ //获取当前日期字符串返回
  let nowDate =  new Date();
  return nowDate.getFullYear() + '-' + (nowDate.getMonth() + 1) +'-' +nowDate.getDate();
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShow:false,
    editable:true,
    numList: [{
      name: '第一步'
    }, {
      name: '第二步'
    }, {
      name: '第三步'
    }],
    num:0,
    baseUrl:__config.basePath,
    camaraType:'',
    sexs:[
      {id:'W',text:'女'},
      {id:'M',text:'男'}
    ],
    types:[
      {id:'0',text:'临促'},
      {id:'1',text:'长促'},
      {id:'2',text:'理货员'},
    ],
    date:getNowDate2(),
    sex_index:0,
    type_index:0,
    frontid:'',
    reverseid:'',
    frontbank:'',
    faceid:'',
    refuserid:'U100',
    userid:'',
    user:{
    },
    bankcard:'',
    bankname:'',
    username:'',
    cardid:'',

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getShow();
    this.getUser();
    let url = options.q;
    url = JSON.stringify(decodeURIComponent(options.q))
    //app.dialog.success(url)
    //url = 'http://jderp.vicp.net:10028/kxpht/apps/user?userid=U100'
    if(url.indexOf('?') == -1){
      return;
    }
    let param = url.substring(url.indexOf('?') +1)
    if(param.indexOf('=') == -1){
      return;
    }
    let id = param.substring(param.indexOf('=') + 1)
    console.log(id.replace('"',''))

    this.setData({
      refuserid: id.replace('"','')
    })
    
    this.setData({
      date:this.getNowDate()
    })
    //this.getUserid()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  changeSex(event){
    this.setData({
      sex_index : event.detail.value
    })
  },
  changeType(event){
    this.setData({
      type_index: event.detail.value
    })
  },
  openCanmera(e){
    let type = e.currentTarget.dataset.type
    this.setData({
      camaraType:type
    })
    wx.navigateTo({
      url: '/pages/takePhoto/takePhoto'
    })
  },
  openFrontCanmera(e){
    let type = e.currentTarget.dataset.type
    this.setData({
      camaraType:type
    })
    wx.navigateTo({
      url: '/pages/facePhoto/facePhoto'
    })
  },
  addImg(img){
    this.editImg(img)
  },
  DelImg(e){
    let type = e.currentTarget.dataset.type
    if(type== 'frontid'){
      this.setData({
        frontid:''
      })
    }else if(type == 'reverseid'){
        this.setData({
          reverseid:''
      })
    }else if(type == 'frontbank'){
        this.setData({
          frontbank:''
      })
    }else if(type == 'faceid'){
        this.setData({
          faceid:''
      })
    }
  },
  editImg(url){
    // if(this.data.camaraType == 'frontbank'){
    //   this.getBankCard(url)
    // }else if(this.data.camaraType == 'reverseid'){
    //   //https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E9%93%B6%E8%A1%8C%E5%8D%A1&hs=0&pn=3&spn=0&di=180510&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&ie=utf-8&oe=utf-8&cl=2&lm=-1&cs=1641127553%2C865688794&os=2245991157%2C944563271&simid=3480638204%2C403756757&adpicid=0&lpn=0&ln=30&fr=ala&fm=&sme=&cg=&bdtype=0&oriquery=%E9%93%B6%E8%A1%8C%E5%8D%A1&objurl=https%3A%2F%2Fss0.baidu.com%2F7Po3dSag_xI4khGko9WTAnF6hhy%2Fbaike%2Fc0%3Dbaike80%2C5%2C5%2C80%2C26%2Fsign%3Df4c4825b530fd9f9b41a5d3b4444bf4f%2F314e251f95cad1c8b8ba51007d3e6709c93d5197.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fkwthj_z%26e3Bkwt17_z%26e3Bv54AzdH3Frtvp76jAzdH3F9c8n80lAzdH3F9c8n80lAzdH3FaAzdH3Fn89jdc8ulcvw18vbkbkwc8aa01njm0alvln1c8l0&gsm=4&islist=&querylist=
    //   //https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E8%BA%AB%E4%BB%BD%E8%AF%81%E6%AD%A3%E5%8F%8D%E9%9D%A2%E7%85%A7%E7%89%87%E5%9B%BE%E7%89%87&step_word=&hs=0&pn=2&spn=0&di=9570&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=-1&cs=3375693451%2C2520940449&os=2017255879%2C920165898&simid=4282653950%2C721686787&adpicid=0&lpn=0&ln=110&fr=&fmq=1624687428972_R&fm=rs2&ic=undefined&s=undefined&hd=undefined&latest=undefined&copyright=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=%E8%BA%AB%E4%BB%BD%E8%AF%81%E5%8F%8D%E9%9D%A2&objurl=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%3A%2F%2Ftpic.home.news.cn%2FxhBlog%2Fxhpic001%2FM01%2F5A%2FB1%2FwKhTglQqFvcEAAAAAAAAAAAAAAA979.jpg%26refer%3Dhttp%3A%2F%2Ftpic.home.news.cn%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Djpeg%3Fsec%3D1627279649%26t%3D96cdb0102bcd6d1fcaf697611fbcfc12&fromurl=ippr_z2C%24qAzdH3FAzdH3Fkt2c_z%26e3Bgjof_z%26e3BvgAzdH3F2wpjAzdH3Fkt2cAzdH3F1zc8ndd_z%26e3Bi54j_z%26e3Bgjof_z%26e3BvgAzdH3Fr56pwsAzdH3Ft42fAzdH3Fb0maadAzdH3F8AzdH3F8a&gsm=4&rpstart=0&rpnum=0&islist=&querylist=&nojc=undefined
    //   this.getIdCard(url)
      
    // }else{
    //   this.imgUpload(url);
    // }
     this.imgUpload(url);
  },
  imgUpload(url){
    app.api.imgUpload(url).then(res => {
      if(this.data.camaraType == 'frontid'){
        this.setData({
          frontid:res.imageurl
        })
      }else if(this.data.camaraType == 'reverseid'){
          this.setData({
            reverseid:res.imageurl
        })
        this.getIdCard()
      }else if(this.data.camaraType == 'frontbank'){
        this.setData({
          frontbank:res.imageurl
        })
        this.getBankCard();
      }
      else if(this.data.camaraType == 'faceid'){
        this.setData({
          faceid:res.imageurl
      })
    }
    })
  },
  submit(event){
    let that = this;
    let data = event.detail.value
    data.sex = this.data.sexs[this.data.sex_index].id
    data.type = this.data.types[this.data.type_index].id
    data.frontid = this.data.frontid
    data.reverseid = this.data.reverseid
    data.frontbank = this.data.frontbank
    data.faceid = this.data.faceid
    data.refuserid = this.data.refuserid
    data.userid = data.mobi
    data.password = '123456'

    //data.refuserid = undefined;

    if(!data.refuserid){
      wx.showModal({
        title: '提示',
        editable: true,
        placeholderText: "请输入上级业务员账号",
        showCancel: false,
        success (res) {
          if(res.content){
            data.refuserid = res.content;

            that.setData({
              refuserid: res.content
             })

             if(that.validateSubmit(data)){
              app.api.saveprom(data).then(res =>{
                app.dialog.success(res.info)
                wx.navigateTo({
                  url: '../login/login',
                })
              })
            }
          }else{
            wx.showToast({
              title: '请输入上级账号',
            })
          }
        }
      })      
    }else{
      if(this.validateSubmit(data)){
        app.api.saveprom(data).then(res =>{
          app.dialog.success(res.info)
          wx.navigateTo({
            url: '../login/login',
          })
        })
      }
    }
  },
  ViewImage(e){
    let url = this.data.baseUrl + e.currentTarget.dataset.url
    console.log(url)
    wx.previewImage({
      urls: [url] // 需要预览的图片http链接列表
    })
  },
   /**
  * 扫码事件
  */
 scanCodeEvent: function(){
   var that = this;
   wx.scanCode({
     onlyFromCamera: true,// 只允许从相机扫码
     success(res){
       console.log("扫码成功："+JSON.stringify(res))
       // 扫码成功后  在此处理接下来的逻辑
       /*
       that.setData({
        refuserid: res.result
       })
       */
     }
   })
  },
  getNowDate:function(){ //获取当前日期字符串返回
    let nowDate =  new Date();
    return nowDate.getFullYear() + '-' + (nowDate.getMonth() + 1) +'-' +nowDate.getDate();
  },
  getUserid:function(){ //获取用户账号
    let that = this;
    app.api.getUserid().then(res =>{
      that.setData({
        userid:res.userid
      })
    })
  },
  validateSubmit(obj){
    let msg = ''
    if(validate.validatenull(obj.password)){
      msg = '用户密码';
    }else if(validate.validatenull(obj.username)){
      msg = '用户姓名';
    }else if(validate.validatenull(obj.cardid)){
      msg = '用户身份证';
    }else if(validate.validatenull(obj.mobi)){
      msg = '用户手机号'
    }else if(validate.validatenull(obj.bankcard)){
      msg = '银行卡号';
    }else if(validate.validatenull(obj.frontid)){
      msg = '身份证正面图片';
    }else if(validate.validatenull(obj.reverseid)){
      msg = '身份证背面图片';
    }else if(validate.validatenull(obj.frontbank)){
      msg = '银行卡正面图片';
    }else if(validate.validatenull(obj.econtact)){
      msg = '紧急联系人姓名';
    }else if(validate.validatenull(obj.econtactnumber)){
      msg = '紧急联系人手机';
    }else{
      return true;
    }
    wx.showModal({
      title: '提示',
      content: msg + '不能为空',
      showCancel:false
    })
    return false;
  },
  getUser(){
    wx.login({
      success:res =>{
        let data = {'code':res.code}
        app.api.getUserInfo(data).then(res => {
          if(res.rows != undefined && res.rows != null){
            this.setData({
              editable:false,
              user:res.rows,
              frontid:res.rows.frontid,
              reverseid:res.rows.reverseid,
              frontbank:res.rows.frontbank,
              faceid:res.rows.faceid,
              sex_index:res.rows.sex == 'W' ? 0 : 1
            })
          }
        })
      }
    })
  },
  getBankCard(url){
    let img = wx.getFileSystemManager().readFileSync(url, "base64")
    let data = {base64Img : img}
    app.api.bankcard(data).then(res => {
      if(res.data != undefined && res.data != null){
        if(res.data.cardNo != this.data.user.bankcard){
          wx.showModal({
            title: '提示',
            content: '识别的银行卡账号为'+res.data.cardNo+'与填写账号不一致',
            showCancel:false
          })
        }else if(res.data.bankInfo.substring(0,res.data.bankInfo.indexOf('(')) != this.data.user.bankname){
          wx.showModal({
            title: '提示',
            content: '识别的银行为'+res.data.bankInfo.substring(0,res.data.bankInfo.indexOf('(')) +'与填写银行不一致',
            showCancel:false
          })
        }else{
          //this.imgUpload(url)
        }
      }else{
        wx.showModal({
          title: '提示',
          content: '图片识别失败',
          showCancel:false
        })
      }
    })
  },
  getIdCard(url){
    let img = wx.getFileSystemManager().readFileSync(url, "base64")
    let data = {base64Img : img}
    app.api.idCard(data).then(res => {
      if(res.data != undefined && res.data != null){
        if(res.data.idNum != this.data.user.cardid){
          wx.showModal({
            title: '提示',
            content: '识别的身份证号为'+res.data.idNum+'与填写的身份证号不一致',
            showCancel:false
          })
        }else if(res.data.name != this.data.user.username){
          wx.showModal({
            title: '提示',
            content: '识别的身份证姓名'+res.data.name+'与填写的姓名不一致',
            showCancel:false
          })
        }else if(res.data.sex != this.data.sexs[this.data.sex_index].text){
          wx.showModal({
            title: '提示',
            content: '识别的身份证性别'+res.data.sex+'与填写的不一致' ,
            showCancel:false
          })
        }else{
          this.imgUpload(url)
        }
      }else{
        wx.showModal({
          title: '提示',
          content: '身份证识别失败',
          showCancel:false
        })
      }
    })
  },
  bindTimeChange(e){
    this.setData({
      date:e.detail.value
    })
  },
  inpbankname(e){
    this.setData({
      'user.bankname':e.detail.value
    })
  },
  inpbankcard(e){
    this.setData({
      'user.bankcard':e.detail.value
    })
  },
  inpusername(e){
    this.setData({
      'user.username':e.detail.value
    })
  },
  inpcardid(e){
    this.setData({
      'user.cardid':e.detail.value
    })
  },
  getShow(){
    app.api.showIdcard().then(res => {
      this.setData({
        isShow:res.data
      })
    })
  }
  //wx.getFileSystemManager().readFileSync(path, "base64")
})